﻿using DryIoc;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace AbpPcClient.WpfClient.Service.Common
{
    public  class HttpAbpApiRequestTools
    {
        public static string apiHost = "https://localhost:44311/";
        public static string apiServicePrefixUrl = apiHost + "api/services/app/";
        public static string token = "";
        /// <summary>
        /// 返回一般错误
        /// </summary>
        /// <param name="errorMess"></param>
        /// <returns></returns>
        public static ResultModel InitErrorAllResult(string errorMess)
        {
            return new ResultModel()
            {
                Success = false,
                Error = new ErrorInfo()
                {
                    Code = (int)ResultCode.ErrorAll,
                    Message = errorMess
                }
            };
        }
        /// <summary>
        /// 返回参数错误
        /// </summary>
        /// <param name="errorMess"></param>
        /// <returns></returns>
        public static ResultModel InitParamsErrorResult(string errorMess)
        {
            return new ResultModel()
            {
                Success = false,
                Error = new ErrorInfo()
                {
                    Code = (int)ResultCode.ParamsError,
                    Message = errorMess
                }
            };
        }
        /// <summary>
        /// 发起Get请求
        /// </summary>
        /// <param name="url">请求Url</param>
        /// <param name="queryParams">请求参数</param>
        /// <param name="headerParams">请求头部参数</param>
        /// <param name="contentType">请求内容类型</param>
        /// <param name="timeOut">超时时间 单位:秒</param>
        /// <returns></returns>
        public static ResultModel Get(string url, Dictionary<string, string> queryParams = null, Dictionary<string, string> headerParams = null, int timeOut = 30)
        {

            if (string.IsNullOrEmpty(url))
            {
                return InitParamsErrorResult("Url不能是空的");
            }
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = new TimeSpan(0, 0, timeOut);
                    if (headerParams != null)
                    {
                        foreach (var header in headerParams)
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }

                    string strQueryParams = "";
                    if (queryParams != null)
                    {
                        url = url + "?";
                        foreach (var param in queryParams)
                        {
                            url += param.Key + "=" + param.Value + "&";
                        }
                        url = url.TrimEnd('&');
                    }

                    string response = client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(response))
                        return JsonConvert.DeserializeObject<ResultModel>(response);  //序列化json

                    return InitErrorAllResult("返回信息为null");


                }
            }
            catch (Exception ex)
            {
                return InitErrorAllResult(ex.ToString());
            }

        }
        /// <summary>
        /// 发起基于token的Get请求
        /// </summary>
        /// <param name="method"></param>
        /// <param name="queryParams"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static ResultModel GetByToken(string method, Dictionary<string, string> queryParams = null, int timeOut = 30)
        {
            if (string.IsNullOrEmpty(token))
            {
                return InitErrorAllResult("没有请求的Token");
            }
            if (string.IsNullOrEmpty(method))
            {
                return InitParamsErrorResult("method不能是空的");
            }
            string url = apiServicePrefixUrl + method;
            Dictionary<string, string> header = new Dictionary<string, string>()
            {
                { "Authorization","Bearer "+token }
            };
            return Get(url, queryParams, header, timeOut);
        }
        /// <summary>
        /// 发起基于token的Get请求
        /// </summary>
        /// <param name="method"></param>
        /// <param name="queryObj"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static ResultModel GetByToken<T>(string method, T queryObj, int timeOut = 30)
        {
            Dictionary<string, string> queryParams = ObjectToMap(queryObj);
            return GetByToken(method, queryParams, timeOut);
        }
        /// <summary>
        /// 发起Post请求
        /// </summary>
        /// <param name="url">请求url</param>
        /// <param name="body">请求内容</param>
        /// <param name="contentType">请求内容类型</param>
        /// <param name="headerParams">请求头部参数</param>
        /// <param name="timeOut">超时时间</param>
        /// <returns></returns>
        public static ResultModel Post<T>(string url, T body, string contentType = "application/json", Dictionary<string, string> headerParams = null, int timeOut = 30)
        {
            if (string.IsNullOrEmpty(url))
            {
                return InitParamsErrorResult("Url不能是空的");
            }
            string json = "";
            if (body != null)
            {
                json = JsonConvert.SerializeObject(body);
            }

            using (HttpClient client = new HttpClient())
            {
                client.Timeout = new TimeSpan(0, 0, timeOut);
                if (headerParams != null)
                {
                    foreach (var header in headerParams)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                using (HttpContent httpContent = new StringContent(json, Encoding.UTF8))
                {
                    if (contentType != null)
                        httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);

                    string result = client.PostAsync(url, httpContent).Result.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(result))
                        return JsonConvert.DeserializeObject<ResultModel>(result);  //序列化json

                    return InitErrorAllResult("返回信息为null");
                }
            }
        }

        public static ResultModel PostByToken<T>(string method, T body, string contentType = "application/json", int timeOut = 30)
        {
            if (string.IsNullOrEmpty(token))
            {
                return InitErrorAllResult("没有请求的Token");
            }
            if (string.IsNullOrEmpty(method))
            {
                return InitParamsErrorResult("method不能是空的");
            }

            string url = apiServicePrefixUrl + method;
            Dictionary<string, string> header = new Dictionary<string, string>()
            {
                { "Authorization","Bearer "+token }
            };
            return Post(url, body, contentType, header, timeOut);


        }
        #region 对象转成字典
        /// <summary>
        /// 对象转换为字典
        /// </summary>
        /// <param name="obj">待转化的对象</param>
        /// <returns></returns>
        public static Dictionary<string, string> ObjectToMap(object obj)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();

            Type t = obj.GetType(); // 获取对象对应的类， 对应的类型

            PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 获取当前type公共属性

            foreach (PropertyInfo p in pi)
            {
                MethodInfo m = p.GetGetMethod();
                if (m != null && m.IsPublic)
                {
                    // 进行判NULL处理
                    if (m.Invoke(obj, new object[] { }) != null)
                    {
                        map.Add(p.Name, m.Invoke(obj, new object[] { }).ToString()); // 向字典添加元素
                    }
                }
            }
            return map;
        }
        #endregion
    }
    /// <summary>
    /// 接口执行状态码
    /// </summary>
    public enum ResultCode
    {
        /// <summary>
        /// 所有错误
        /// </summary>
        ErrorAll = -10000,
        /// <summary>
        /// 参数错误
        /// </summary>
        ParamsError = -10001,
    }
}
